//
//  TogetherLocationSelectorViewController.m
//  Together_iOS
//
//  Created by applex on 14-3-1.
//  Copyright (c) 2014年 QIU Shuang. All rights reserved.
//

#import "TogetherLocationSelectorViewController.h"
#import "AFNetworking.h"
#import "TogetherHttpClient.h"

@interface TogetherLocationSelectorViewController () <UITableViewDataSource, UITableViewDelegate>


@end

@implementation TogetherLocationSelectorViewController

- (id)init
{
    self = [super init];
    if (self) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return self;
}


- (void)loadView {
    [super loadView];
    _tableView.frame = self.view.bounds;
    [self.view addSubview:_tableView];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
	self.title = [self.region objectForKey:@"district_name"];
    [self.tableView reloadData];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.region) {
        return 0;
    }
    return [[self.region objectForKey:@"neighborhoods"] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"LocationSelectorCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    cell.textLabel.text = [[self.region objectForKey:@"neighborhoods"] objectAtIndex:indexPath.row];

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *regionString = [[self.region objectForKey:@"neighborhoods"] objectAtIndex:indexPath.row];
    [self.settingView didSelectRegion:regionString];
    [self.navigationController popToViewController:self.settingView.viewController animated:YES];
}


#pragma mark - Actions

- (void)refresh {
    NSString *requestUrl = [[TogetherHttpClient serverAddress] stringByAppendingString:@"/cities"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager GET:requestUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

}

@end
